define(['config/appregister',"upfull"],function(app){
    app.directive("videoupload",function(){
        return {
            scope:{conf:"=uploadConf"},
            templateUrl:"app/business/videoupload/directive/template/upload.html",
            link:function(scope,element,attrs){
                accessid = ''
                accesskey = ''
                host = ''
                policyBase64 = ''
                signature = ''
                callbackbody = ''
                filename = ''
                key = ''
                expire = 0
                g_object_name = ''
                g_object_name_type = ''
                now = timestamp = Date.parse(new Date()) / 1000;

                function send_request() {
                    var xmlhttp = null;
                    if(window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    } else if(window.ActiveXObject) {
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    if(xmlhttp != null) {
                        serverUrl = "http://"+allUrl+":8089/elink_aliyun/api/oss/getMediaOSSAuth?seed="+localStorage["seed"]+"&authToken="+localStorage["authToken"]
                        xmlhttp.open("GET", serverUrl, false);
                        xmlhttp.send(null);
                        return xmlhttp.responseText
                    } else {
                        alert("Your browser does not support XMLHTTP.");
                    }
                };

                function check_object_radio() {
                    g_object_name_type = 'random_name';
                }

                function timeStamp( second_time ){

                    var time = parseInt(second_time) + "秒";
                    if( parseInt(second_time )> 60){

                        var second = parseInt(second_time) % 60;
                        var min = parseInt(second_time / 60);
                        time = min + "分" + second + "秒";

                        if( min > 60 ){
                            min = parseInt(second_time / 60) % 60;
                            var hour = parseInt( parseInt(second_time / 60) /60 );
                            time = hour + "小时" + min + "分" + second + "秒";

                            if( hour > 24 ){
                                hour = parseInt( parseInt(second_time / 60) /60 ) % 24;
                                var day = parseInt( parseInt( parseInt(second_time / 60) /60 ) / 24 );
                                time = day + "天" + hour + "小时" + min + "分" + second + "秒";
                            }
                        }


                    }

                    return time;
                }

                function get_signature() {
                    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
                    now = timestamp = Date.parse(new Date()) / 1000;
                    if(expire < now + 3) {
                        body = send_request()
                        var obj = eval("(" + body + ")");
                        host = obj['host']
                        policyBase64 = obj['policy']
                        accessid = obj['accessid']
                        signature = obj['signature']
                        expire = parseInt(obj['expire'])
                        callbackbody = obj['callback']
                        key = obj['dir']
                        return true;
                    }
                    return false;
                };

                function random_string(len) {
                    len = len || 32;
                    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                    var maxPos = chars.length;
                    var pwd = '';
                    for(i = 0; i < len; i++) {
                        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
                    }
                    return pwd;
                }

                function get_suffix(filename) {
                    pos = filename.lastIndexOf('.')
                    suffix = ''
                    if(pos != -1) {
                        suffix = filename.substring(pos)
                    }
                    return suffix;
                }

                function calculate_object_name(filename) {
                    if(g_object_name_type == 'local_name') {
                        g_object_name += "${filename}"
                    } else if(g_object_name_type == 'random_name') {
                        suffix = get_suffix(filename)
                        g_object_name = key + random_string(10) + suffix
                    }
                    return ''
                }

                function get_uploaded_object_name(filename) {
                    if(g_object_name_type == 'local_name') {
                        tmp_name = g_object_name
                        tmp_name = tmp_name.replace("${filename}", filename);
                        return tmp_name
                    } else if(g_object_name_type == 'random_name') {
                        scope.$emit("file",g_object_name);
                        return g_object_name
                    }
                }

                function set_upload_param(up, filename, ret) {
                    if(ret == false) {
                        ret = get_signature()
                    }
                    g_object_name = key;
                    if(filename != '') {
                        suffix = get_suffix(filename)
                        calculate_object_name(filename)
                    }
                    new_multipart_params = {
                        'key': g_object_name,
                        'policy': policyBase64,
                        'OSSAccessKeyId': accessid,
                        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                        'callback': callbackbody,
                        'signature': signature,
                    };

                    up.setOption({'url': host,
                        'multipart_params': new_multipart_params
                    });

                    up.start();
                }

                function get_current_speed (up) {
                    var speed = up.total.bytesPerSec;
                    if (speed > 1024 * 1024) {
                        return (speed / (1024 * 1024)).toFixed(2) + ' MB/S';
                    } else if (speed > 1024) {
                        return Math.ceil(speed / 1024) + ' KB/S';
                    }
                }

                function get_last_time (up, file) {
                    var speed = up.total.bytesPerSec;
                    var origSize = file.origSize;
                    var loaded = file.loaded;
                    var lastTimeStamp  =  (origSize - loaded) / speed;
                    return timeStamp(Math.floor(lastTimeStamp));

                }
                var speed = '0 KB/S';
                var lastTime = '剩余时间: 0秒';
                var percent = "0 %"
                var uploadStatus = 0;
                function display_speed() {
                    if (document.getElementById('speedText') != null) {
                        document.getElementById('speedText').innerHTML = '上传速度:'+ speed;
                    }
                };
                function display_last_time () {
                    if (document.getElementById('lastTimeText') != null) {
                        document.getElementById('lastTimeText').innerHTML = '剩余时间:' + lastTime;
                    }
                }
                function display_percent () {
                    if (document.getElementById('percent') != null) {
                        document.getElementById('percent').innerHTML = '剩余时间:' + lastTime;
                    }
                }
                var speedInterval = setInterval(display_speed, 1000);
                var lastTimeInterval = setInterval(display_last_time, 1000);
                var uploader = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',
                    browse_button: 'selectfiles',
                    //multi_selection: false,
                    container: document.getElementById('container'),
                    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
                    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
                    url: 'http://oss.aliyuncs.com',

                    filters: {
                        mime_types: [ //只允许上传图片和zip,rar,video文件
                            {
                                title: "Video files",
                                extensions: "3GP,AVI,FLV,MP4,M3U8,MPG,ASF,WMV,MKV,MOV,TS,WebM"
                            }
                        ],
                        max_file_size: '1000mb', //最大只能上传10mb的文件
                        prevent_duplicates: true //不允许选取重复文件
                    },

                    init: {
                        PostInit: function() {
                            document.getElementById('ossfile').innerHTML = '';
                        },

                        FilesAdded: function(up, files) {
                            scope.$emit("uploadSuccess")
                           /* + file.name + ' (' + plupload.formatSize(file.size) + ')*/
                            set_upload_param(uploader, '', false);
                            plupload.each(files, function(file) {
                                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '"><b style="display: block;margin-bottom: 10px;font-weight: normal; color: #999;font-size: 14px;"></b>' +
                                    '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
                                    '<div id="speedText" style="float: left;color: #999;"></div><div id="lastTimeText" style="float: left;color: #999;margin-left: 125px;"></div>' +
                                    '<div id="percent" style=" color: #999;float: right;margin-right: 105px;margin-top: -49px;font-size: 16px;color: #30a3ff;">'+file.percent+'</div>' +
                                    '<div id="nonesend" style="float:right;margin-top: -26px;margin-right: 21px;padding-left: 20px;background: url(them/imgs/delete.jpg) 0 1px no-repeat;">取消上传</div></div>';
                            });
                            document.getElementById("nonesend").onclick=function(){
                                location.reload()
                            }
                        },

                        BeforeUpload: function(up, file) {
                            check_object_radio();
                            set_upload_param(up, file.name, true);
                        },

                        UploadProgress: function(up, file) {
                            var d = document.getElementById(file.id);
                            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.name + "</span>";
                            document.getElementById('percent').innerHTML = '<span>' + file.percent + "%</span>";
                            var prog = d.getElementsByTagName('div')[0];
                            var progBar = prog.getElementsByTagName('div')[0]
                            progBar.style.width = 11.5 * file.percent + 'px';
                          /*  progBar.setAttribute('aria-valuenow', file.percent);*/
                           /* progBar.setAttribute('aria-valuenow', file.percent);*/
                            // 实时显示上传速率
                            speed = get_current_speed(up)
                            lastTime = get_last_time(up, file);
                        },

                        FileUploaded: function(up, file, info) {
                            clearInterval(speedInterval);
                            clearInterval(lastTimeInterval);
                            uploadStatus = 1;
                            scope.$emit("uploadS",uploadStatus)
                            if(info.status == 200) {
                                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML =file.name ;
                                get_uploaded_object_name(file.name)
                            } else {
                                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                            }
                        },

                        Error: function(up, err) {
                            if(err.code == -600) {
                                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
                            } else if(err.code == -601) {
                                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
                            } else if(err.code == -602) {
                                document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
                            } else {
                                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
                            }
                        }
                    }
                });

                uploader.init();

            }
        }
    });
});




















